module.exports = function(sequelize, DataTypes) {
  var helper = require('../lib/merge')
  var rating = require('./mixins/RatingMixin')

  var Answer = sequelize.define(
    'Answer',
    helper.mergeWithArray(
      {
        id: {
          type: DataTypes.BIGINT,
          primaryKey: true,
          autoIncrement: true
        },
        data: {
          type: DataTypes.JSON,
          comment: 'data in json form',
          allowNull: false,
          validate: {
            notEmpty: function(obj) {
              if (Object.keys(obj).length === 0) {
                throw new Error('Data is required!')
              }
            }
          }
        },
        costSeconds: {
          type: DataTypes.INTEGER,
          comment: 'Total seconds cost in this task'
        },
        userInfo: {
          type: DataTypes.JSON,
          comment: 'user info to be displayed in lists'
        },
        state: {
          type: DataTypes.ENUM('start', 'done', 'check', 'redo'),
          comments: 'State of the answer'
        },
        unreadCount: {
          type: DataTypes.TINYINT(1),
          defaultValue: 1,
          comment: 'New answers are unread'
        }
      },
      rating(DataTypes).attributes
    ),
    helper.mergeWithArray(
      {
        tableName: 'answers',
        paranoid: true,
        indexes: [
          {
            name: 'updated_at_idx',
            fields: ['updatedAt']
          },
          {
            name: 'progress_id_idx',
            fields: ['progressId']
          },
          {
            name: 'document_id_idx',
            fields: ['documentId']
          },
          {
            name: 'version_id_idx',
            fields: ['versionId']
          },
          {
            name: 'task_id_idx',
            fields: ['taskId']
          },
          {
            name: 'user_id_idx',
            fields: ['userId']
          },
          {
            name: 'state_idx',
            fields: ['state']
          },
          {
            name: 'unread_count_idx',
            fields: ['unreadCount']
          }
        ],
        comments: 'Answers for Task'
      },
      rating(DataTypes).options
    )
  )

  Answer.associate = function(models) {
    this.belongsTo(models.Task, {
      as: 'Tasks',
      foreignKey: 'taskId',
      constraints: false
    })
    this.belongsTo(models.Progress, {
      as: 'Progresses',
      foreignKey: 'progressId',
      constraints: false
    })
    this.belongsTo(models.Document, {
      as: 'Prototype',
      foreignKey: 'documentId',
      constraints: false
    })
    this.belongsTo(models.Document, {
      as: 'Version',
      foreignKey: 'versionId',
      constraints: false
    })
    this.belongsTo(models.User, {
      as: 'Owner',
      foreignKey: 'userId',
      constraints: false
    })
  }
  return Answer
}
